package top.haichi.webpaper.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import top.haichi.webpaper.entity.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class InterceptorUtils {

    /**
     * 在Interceptor中返回result
     *
     * @param responseResult
     * @param response
     * @throws IOException
     */
    public static void result(Result responseResult, HttpServletResponse response)  {
        String json = JSONObject.toJSONString(responseResult);
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在Interceptor中根据request返回body且不影响request的输入流
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestBody(HttpServletRequest request) {
        ContentCachingRequestWrapper requestWapper = null;
        if(request instanceof HttpServletRequest){
            requestWapper = (ContentCachingRequestWrapper) request;
        }
        String body = null;
        try {
            body = IOUtils.toString(requestWapper.getBody(),request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
}
